package com.example.partner.activity.team;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.example.partner.R;
import com.example.partner.activity.home.ImageDisplayActivity;
import com.example.partner.adapter.team.TeamViewPagerAdapter;
import com.example.partner.common.BaseResponse;
import com.example.partner.common.TeamInfoViewModel;
import com.example.partner.model.request.TeamQuitRequest;
import com.example.partner.service.TeamService;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class TeamInfoActivity extends AppCompatActivity {
    ImageView avatar;
    TextView tvteamname,description;
    Button btjoin,setpwddialog_bt_cancel,setpwddialog_bt_conf;
    TeamService teamService;
    final String TAG = "TeamInfoActivity";
    String teamname,descript,img;
    Long id,userid;
    Boolean isjoin;
    Integer status;
    EditText setpwddialog_et_pwd;
    AlertDialog alertDialog;
    private TeamInfoViewModel viewModel;
    TeamViewPagerAdapter viewPagerAdapter;
    ViewPager2 viewPager;
    TabLayout tabLayout;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.team_info);
        //获取登录用户的id
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        userid=sharedPreferences.getLong("userId",-1);
        //创建Retrofit实例，设置其基本URL和转换工厂，然后创建一个特定类型的服务接口实例，以便稍后使用该服务发起HTTP请求。
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        teamService = retrofit.create(TeamService.class);
        //获取组件
        btjoin=findViewById(R.id.joinTeam);
        tvteamname=findViewById(R.id.teamName);
        description=findViewById(R.id.description);
        avatar=findViewById(R.id.teamImg);
        viewPager=findViewById(R.id.teamConcernViewPager);
        tabLayout=findViewById(R.id.teamTabLayout);

        //把数据存入viewModel中方便与fragment进行数据传递
        viewModel = new ViewModelProvider(this).get(TeamInfoViewModel.class);
//        获取上一个activity传过来的信息，存入viewModel并展示在页面上
        showTeamDetail();
//        控制按钮的显示
        joinOrQuit();
        // 在 onCreate 中设置 ViewPager 和 TabLayout
        viewPagerAdapter = new TeamViewPagerAdapter(this);
        viewPager.setAdapter(viewPagerAdapter);
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            // 设置标签的文本
            switch (position) {
                case 0:
                    tab.setText("详细信息");
                    break;
                case 1:
                    tab.setText("公告");
                    break;
                case 2:
                    tab.setText("队伍成员");
                    break;
            }
        }).attach();
//        加入退出按钮的点击事件
        btjoin.setOnClickListener(view -> {
            submitJoinOrQuit();
        });
        //点击队伍图片放大查看
        avatar.setOnClickListener(view -> {// 启动新的Activity或DialogFragment来显示图片
            Intent avatarIntent = new Intent(TeamInfoActivity.this, ImageDisplayActivity.class);
            avatarIntent.putExtra("image_url", img);
            startActivity(avatarIntent);
        });
    }

    private void joinOrQuit() {
        teamService.isJoin(userid,id).enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 处理成功的响应
                    isjoin = response.body().getData();
                    if (isjoin){
                        btjoin.setText("默默退出");
                    }
                    // 更新UI或处理数据
                } else {
                    // 处理错误情况
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });

    }
    private void submitJoinOrQuit() {
        String text = btjoin.getText().toString();//根据按钮名称判断当前用户是加入队伍还是退出
        if (text.equals("我要加入")) {//加入
            if (status.equals(0)) {
                join(userid, id, "");//调用加入队伍方法
            }
            if (status.equals(2)) {//如果加入的是加密队伍，要显示输入密码
                showinputPwdDialog();
            }
        } else {//退出
            quit();//调用退出队伍方法
        }
    }
    private void quit() {
        TeamQuitRequest request = new TeamQuitRequest();
        request.setTeamId(id);
        request.setUserId(userid);
        teamService.quitTeam(request).enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {
                BaseResponse<Boolean> responseBody = response.body();
                String message = responseBody.message;
                if (response.isSuccessful()) {
                    new android.app.AlertDialog.Builder(TeamInfoActivity.this)
                            .setTitle("退出") // 设置对话框标题
                            .setMessage("真舍不得你") // 设置要显示的消息
                            .setPositiveButton("知道了", (dialog, which) -> { // 用户点击确定按钮后的操作
                            })
                            .show();
                    btjoin.setText("我要加入");
                } else {
                    Toast.makeText(TeamInfoActivity.this,message,Toast.LENGTH_SHORT).show();
                    // 处理错误情况
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {
                // 网络错误处理
                Log.e(TAG, "post回调失败：" + t.getMessage() + "," + t.toString());
                Toast.makeText(TeamInfoActivity.this, t.getMessage()+"post回调失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void showinputPwdDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(TeamInfoActivity.this);// 创建悬浮页面对象
        View view = View.inflate(this, R.layout.password_dialog, null);
        builder.setView(view);
        alertDialog=builder.show();
        setpwddialog_bt_cancel=view.findViewById(R.id.setpwddialog_bt_cancel);
        setpwddialog_bt_conf=view.findViewById(R.id.setpwddialog_bt_conf);
        setpwddialog_et_pwd=view.findViewById(R.id.setpwddialog_et_pwd);
        setpwddialog_bt_cancel.setOnClickListener(v -> alertDialog.dismiss());//设置点击“取消”使对话框消失的点击事件
        setpwddialog_bt_conf.setOnClickListener(v -> {//设置点击“确定”事件
            String password = setpwddialog_et_pwd.getText().toString().trim(); //得到输入框中的密码
            if(TextUtils.isEmpty(password)){//判断输入的密码非空，则提示相关信息
                Toast.makeText(TeamInfoActivity.this, "密码不能为空，请重新输入", Toast.LENGTH_SHORT).show();
            }else{
                join(userid, id, password);//调用加入队伍方法
            }
        });
    }
    public void join(Long userid,Long teamid,String password){
        Map<String, Object> teamjoin = new HashMap<>();
        teamjoin.put("userid",userid);
        teamjoin.put("teamid",teamid);
        teamjoin.put("password",password);
        teamService.joinTeam(teamjoin).enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {
                if (response.isSuccessful()&&response.body().getData()) {
                    // 处理成功的响应
                    Toast.makeText(TeamInfoActivity.this,"加入队伍成功！",Toast.LENGTH_SHORT).show();
                    // 创建AlertDialog
                    new android.app.AlertDialog.Builder(TeamInfoActivity.this)
                            .setTitle("加入") // 设置对话框标题
                            .setMessage("恭喜成为队伍的一员") // 设置要显示的消息
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 用户点击确定按钮后的操作
                            })
                            .show();
                    btjoin.setText("默默退出");
                } else {
                    Toast.makeText(TeamInfoActivity.this,response.body().getMessage(),Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {
                // 网络错误处理
                Toast.makeText(TeamInfoActivity.this, t.getMessage()+"post回调失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void showTeamDetail() {
        Intent intent = getIntent();

        teamname = intent.getStringExtra("teamname");
        descript=intent.getStringExtra("descript");
        img=intent.getStringExtra("img");
        status=intent.getIntExtra("status",-1);
        id=intent.getLongExtra("teamid",-1);
        String announce=intent.getStringExtra("announce");

        viewModel.setAnnounce(announce);
        viewModel.setId(id);

        description.setText(descript);
        if(img!=null){
            Glide.with(this).load(img).into(avatar);
        }
        tvteamname.setText(teamname);
    }

}